const { isString } = require('./dataType')
let postfix = '_deadtime';
const storage = {
  save (key, value, time) {
    if (!isString(key) || !value) {
      throw new Error(415)
    }
    localStorage.setItem(key, JSON.stringify(value));
    var t = time ? time : 24 * 30;
    var seconds = parseInt(t * 3600);
    if(seconds > 0) {
      var timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000 + seconds;
      localStorage.setItem(key + postfix, timestamp + "")
    } else {
      localStorage.removeItem(key + postfix)
    }
  },
  fetch (key, def) {
    if (!isString(key)) {
      throw new Error(415)
    }
    //return JSON.parse(localStorage.getItem(key)) || null;
      var deadtime = parseInt(localStorage.getItem(key + postfix))
      if (deadtime) {
          if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
              localStorage.removeItem(key);
              localStorage.removeItem(key + postfix);
              if (def) {
                  return def;
              } else {
                  return;
              }
          }
      }
      var res = localStorage.getItem(key);
      if (res) {
          return res;
      } else if (def) {
          return def;
      } else {
          return;
      }
  },
  remove (key) {
    if (!isString(key)) {
      throw new Error(415)
    }
    localStorage.removeItem(key);
  },
  clear () {
    localStorage.clear();
  }
};
module.exports = storage
